import { defineStore } from 'pinia';
import { router }  from '@/router';
import type { RouteRecordRaw } from 'vue-router';
import { staticRoutes } from '~/src/router/routes/staticRoutes';
import { getMenuList, getLocal, transformRouteToVue, filterRouterToAuth, formatJson, authRouterToTree} from '@/utils';
interface RouterStoreProps {
  routerMode: string;
  isInitAuthRoute: boolean;
  menuList: GlobalMenuOption[],
}
export const useRouteStore = defineStore('useRouter-store', {
  state: ():RouterStoreProps => {
    return {
      routerMode: import.meta.env.VITE_APP_ROUTERMODE,
      menuList: [],
      isInitAuthRoute: false
    };
  },
  actions: {
    async initRouter (){
      let routerList: RouteRecordRaw[] = [];
      if(this.routerMode === 'static'){
        routerList =  await this.staticRouter();
      }else {
        await this.dynamicRouter();
      }
      if(Array.isArray(routerList)){
        this.menuList = getMenuList(routerList);
        for(const route of routerList){
          router?.addRoute(route);
        }
        this.isInitAuthRoute = true;
        return true;
      }
      return false;
    },
    dynamicRouter(){
      // 获取用户权限路由;
      const dynamicRouter = formatJson(getLocal('pageAuth'), 2);
      //将权限路由string[][]转换为 tree[]路由
      const authRouter = authRouterToTree(dynamicRouter);
      //过滤路由，只保留有权限的页面
      const adminRouter = filterRouterToAuth(staticRoutes, authRouter);
      return transformRouteToVue(adminRouter);
    },
    staticRouter(){
      //转化为router为vue路由
      return transformRouteToVue(staticRoutes);
    }
  }
});
